package cn.limin.utils;

import cn.limin.domain.Pigeon;

import java.io.*;
import java.util.ArrayList;

public class LmFileHelper {
    public static final String BookDb_PATH= "D:\\Temp\\BookDb.db";

    /**
     * 把集合books保存到文件数据库中
     * @param pigeons
     * @throws IOException
     */
    public static void writePigeons(ArrayList<Pigeon> pigeons)throws IOException {
        File file = new File(BookDb_PATH);

        try(FileOutputStream fs = new FileOutputStream(file);
            ObjectOutputStream oos = new ObjectOutputStream(fs);){
            oos.writeObject(pigeons);
        }

        System.out.println("保存书籍成功!!!");
    }

    /**
     * 从文件数据库中读取书籍到集合中
     * @return
     */
    public static ArrayList<Pigeon> readPigeons() throws IOException, ClassNotFoundException {
        File file = new File(BookDb_PATH);
        ArrayList<Pigeon> pigeons = null;

        if(!file.exists()){
            return null;
        }

        try(FileInputStream fs = new FileInputStream(file);
            ObjectInputStream ois = new ObjectInputStream(fs);){
            pigeons = (ArrayList<Pigeon>) ois.readObject();
        }
        finally {
            return pigeons;
        }
    }
}
